@page "/new"

@using OrleansVoting.Data

@inject PollService PollService
@inject NavigationManager NavigationManager

<h1>Create Poll</h1>

<form @onsubmit="@(e => { })">
	<div class="mb-3">
		<label for="pollTitle" class="form-label">Poll Title</label>
		<input type="text" class="form-control" id="pollTitle" @bind="@question">
		<div id="pollTitleDescription" class="form-text">Enter the question you would like answered.</div>
	</div>
	<div class="input-group mb-3">
		<input type="text" class="form-control" placeholder="Option value" @bind="@newOption">
		<button class="btn btn-outline-secondary" type="button" id="button-add" @onclick="AddOption">Add</button>
	</div>
	@foreach (var (index, option) in options.Select((name, index) => (index, name)))
	{
		<div class="input-group mb-3">
			<input type="text" class="form-control" placeholder="Option value" value="@option" @onchange="@(e => RenameOption(index, e.Value as string))">
			<button class="btn btn-outline-secondary" type="button" id="button-add" @onclick="@(e => DeleteOption(index))">Delete</button>
		</div>
	}

  <button class="btn btn-primary" @onclick="CreatePollAsync">Create</button>
</form>
<br />
<button class="btn btn-danger" @onclick="DemoAutofill">DEMO: auto-fill poll</button>
@code {

    private Guid ownerKey = Guid.NewGuid();
    private List<string> options = new ();
    private string? question;
    private string? newOption;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    private async Task CreatePollAsync()
    {
        if (!string.IsNullOrWhiteSpace(question))
        {
            var pollId = await PollService.CreatePollAsync(question, options);
            NavigationManager.NavigateTo($"/p/{pollId}", forceLoad: true);
        }
    }

    private void AddOption()
    {
        if (!string.IsNullOrWhiteSpace(newOption))
        {
            options.Add(newOption);
            newOption = "";
        }
    }

    private void RenameOption(int index, string? title)
    {
        options[index] = title ?? "";
    }

    private void DeleteOption(int index)
    {
        options.RemoveAt(index);
    }

    private void DemoAutofill()
    {
        question = "What... is your favorite color?";
        options.Clear();
        options.Add("Green");
        options.Add("Red");
        options.Add("Blue. No, yel-auuuuugggh");
        options.Add("Aubergine");
    }
}